
let request = {}
request.isTest = true

let testHost = 'https://pw.qyang.cc'
let testEntry = '/api/'

let host = ''
let entry = ''
request.requestUrl = request.isTest ? testHost + testEntry : host + entry

/**
 * post请求
 * @param {string} url 请求地址
 * @param {object} data 请求参数
 * 2020-08-13
 */
request.post = function(url, data = {}) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: this.requestUrl + url,
			data: data,
			method: 'POST',
			header: {
				'content-type': 'application/json',
				'token': uni.getStorageSync('token')
			},
			dataType: 'json',
			success: res => {
				resolve(res.data)
			},
			fail: res => {
				reject(res)
			}
		})
	})
}

/**
 * 获取数据
 * @param {string} url 请求地址
 * @param {object} data 请求参数
 * @param {object} initial 其他参数
 * @param {boolean} initial.loading false--不显示加载中  true--显示加载中
 * @param {boolean} initial.showErrMsg false--不显示错误文案  true--显示错误文案
 * 2020-08-13
 */
request.getData = function(url, data = {}, initial = {}) {
	let that = this

	if (initial.hasOwnProperty('loading') && initial.loading) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
	}
	
	// 没有定义showErrMsg参数时，默认为true
	if(!initial.hasOwnProperty('showErrMsg')){
		initial.showErrMsg = true
	}

	return new Promise((resolve, reject) => {
		this.post(url, data).then(res => {
			if (initial.hasOwnProperty('loading') && initial.loading) {
				uni.hideLoading()
			}
			if (res.code === 1) {
				resolve(res)
			} else {
				if(res.code == 401){
					getApp().clearToken()
					uni.redirectTo({
						url: '/subpages/login/login'
					})
				} else if (res.code === 0) {
					if (!res.msg) res.msg = '未知错误'
					uni.showToast({
						title:res.msg,
						icon:"none",
						complete() {
							reject(res)
						}
					})
				} else if (initial.showErrMsg) {
					if (!res.msg) res.msg = '未知错误'
					uni.showToast({
						title:res.msg,
						icon:"none",
						complete() {
							resolve(res)
						}
					})
				} else {
					resolve(res)
				}

			}
		}).catch(res => {
			uni.showToast({
				title:'网络异常',
				icon:"none",
				complete() {
					reject(res)
				}
			})
		})
	});
}
request.imgUrl = function(url){
	if(url){
		if(/^http/.test(url)){
			return url;
		}else{
			if(/^\//.test(url)){
				return request.requestUrl+url;
			}else{
				return request.requestUrl+"/"+url;
			}
		}
	}
}
export default request;
